package com.yjkf.zh.admin.controller;

import com.yjkf.zh.admin.aspect.LogAnnotation;
import com.yjkf.zh.admin.model.SysUser;
import com.yjkf.zh.admin.security.JwtAuthenticationToken;
import com.yjkf.zh.admin.security.SecurityUtils;
import com.yjkf.zh.admin.service.SysLoginLogService;
import com.yjkf.zh.admin.service.SysUserService;
import com.yjkf.zh.admin.util.IPUtil;
import com.yjkf.zh.admin.util.LoginBean;
import com.yjkf.zh.admin.util.PasswordUtils;
import com.yjkf.zh.core.http.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class SysLoginController{

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysLoginLogService sysLoginLogService;


    @PostMapping(value = "/login")
    @LogAnnotation(content = "登录")
    public HttpResult login(@RequestBody LoginBean loginBean, HttpServletRequest request){
        String username = loginBean.getAccount();
        String password = loginBean.getPassword();
        SysUser user = sysUserService.findByName(username);

        if(user == null){
            return HttpResult.error("账号不存在");
        }
        if(!PasswordUtils.matches(user.getSalt(),password,user.getPassword())){
            return HttpResult.error("密码不正确");
        }
        if(user.getStatus() == 0){
            return HttpResult.error("账号已被锁定，请联系管理员");
        }

        //保存登录信息到session
        request.getSession().setAttribute("userId",user.getId());
        request.getSession().setMaxInactiveInterval(433200);



        //登录日志
        sysLoginLogService.writeLoginLog(username, IPUtil.getIpAddr(request));
        //系统登录认证
        JwtAuthenticationToken token = SecurityUtils.login(request,username,password,authenticationManager);

        return HttpResult.ok(token);
    }

}
